<?php

namespace app\api\controller;

use app\admin\model\money\Change;
use app\admin\model\product\Listo;
use app\admin\model\product\Order;
use app\admin\model\Suggest;
use app\admin\model\user\Finance;
use app\admin\model\user\Sign;
use app\common\controller\Api;
use app\common\controller\Payment;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $userId = $this->auth->getUser()->id;
        $uinfo = $this->auth->getUser();

        $finance = Finance::where('user_id', $userId)->find();
        $tuijiannumber = '公司';
        if ($uinfo->tuijianid) {
            $tuijiannumber = \app\admin\model\User::where('id', $uinfo->tuijianid)->value('username');
        }

        $where = [
            'tuijianids' => ['like', '%,' . $userId . ',%']
        ];
        $total = \app\admin\model\User::where($where)->count();
        $alipay_info = json_decode($uinfo['alipay_info'], true);

        $recom_url = "http://" . $_SERVER["HTTP_HOST"] . "/dist/index.html#/regist";

        $bank1 = \app\admin\model\user\Banks::where('type', 1)->where('user_id', $userId)->where('status', 1)->find();
        $isBank1 = $bank1 ? 1 : 0;
        $bank2 = \app\admin\model\user\Banks::where('type', 2)->where('user_id', $userId)->where('status', 1)->find();
        $isBank2 = $bank2 ? 1 : 0;

        $data = [
            "id" => $uinfo['id'],
            "username" => $uinfo['username'],
            "nickname" => $uinfo['nickname'],
            "mobile" => $uinfo['mobile'],
            "avatar" => $uinfo['avatar'],
            "createtime" => $uinfo['createtime'],
            "updatetime" => $uinfo['updatetime'],
            "wechat_info" => $uinfo['wechat_info'],
            "wechat_image" => make_full_url($uinfo['wechat_image']),
            "alipay_info" => $alipay_info,
            "invate_code" => $uinfo['invate_code'],
            "achievement" => $uinfo['achievement'],
            "is_partner" => $uinfo['is_partner'],
            "is_houser" => $uinfo['is_houser'],
            "is_operator" => $uinfo['is_operator'],
            "tuijianid" => $uinfo['tuijianid'],
            "tuijiannumber" => $tuijiannumber,
            "tuijianids" => $uinfo['tuijianids'],
            "tdeep" => $uinfo['tdeep'],
            'level' => $uinfo['level'],
            "url" => $uinfo['url'],
            'hasbill' => $finance['hasbill'],
            'hasscore' => $finance['hasscore'],
            'hasmoneys' => $finance['hasmoneys'],
            'hasmoneyd' => $finance['hasmoneyd'],
            'hasmoney' => $finance['hasmoney'],
            'hasshop' => $finance['hasshop'],
            'team_num' => $total,
            'recom_url' => $recom_url,
            'isBank1' => $isBank1,
            'isBank2' => $isBank2
        ];
        $this->success('', $data);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if (!$user) {
            $this->error('该用户尚未注册！');
//        } else {
//            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }

        if ($user->status != 'normal') {
            $this->error(__('Account is locked'));
        }

        //如果已经有账号则直接登录
        $ret = $this->auth->direct($user->id);
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function register()
    {
//        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        $invate_code = $this->request->post('invate_code');

        if (!$password || !$code) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }

        $user = \app\admin\model\User::find();
        if (!$user) {
            $this->error('该系统不可注册！');
        }

        if (!$invate_code) {
            $invate_code = $user->invate_code;
        }

        if (!$invate_code) {
            $this->error('邀请码缺失！');
        }

        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $username = $mobile;
        $ret = $this->auth->register($username, $password, $invate_code, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function profile()
    {
        $user = $this->auth->getUser();
//        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
//        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
//        if ($username) {
//            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
//            if ($exists) {
//                $this->error(__('Username already exists'));
//            }
//            $user->username = $username;
//        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
//        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success('更新成功');
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email 邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo' => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 更新微信收款信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function changeWechat()
    {
        $user = $this->auth->getUser();
        $account = $this->request->post('wechat');
        $image = $this->request->post('image');
        if (!$account || !$image) {
            $this->error(__('Invalid parameters'));
        }

        $user->wechat_info = $account;
        $user->wechat_image = $image;
        $res = $user->save();

        if (!$res) {
            $this->error('更新失败！');
        }

        $this->success('更新成功！');
    }

    /**
     * 更新支付宝收款信息
     */
    public function changeAlipay()
    {
        $user = $this->auth->getUser();
        $account = $this->request->post('account');
        $name = $this->request->post('name');
        if (!$account || !$name) {
            $this->error(__('Invalid parameters'));
        }

        $data = [
            'account' => $account,
            'name' => $name
        ];

        $user->alipay_info = json_encode($data);
        $res = $user->save();

        if (!$res) {
            $this->error('更新失败！');
        }

        $this->success('更新成功！');
    }

    /**
     * 我的团队
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function myTeam()
    {
        $pageSize = $this->request->post('page_size', 15);

        $userId = $this->auth->getUser()->id;
        $where = [
            'tuijianids' => ['like', '%,' . $userId . ',%']
        ];
        $total = \app\admin\model\User::where($where)->count();

        $today = strtotime('today');
        $where['createtime'] = ['>=', $today];

        $total1 = \app\admin\model\User::where($where)->count();

        $yes = $today - 24 * 60 * 60;
        $where['createtime'] = ['>=', $yes];
        $total2 = \app\admin\model\User::where($where)->count();

        $month = strtotime(date("Y-m-01", time()));
        $where['createtime'] = ['>=', $month];
        $total3 = \app\admin\model\User::where($where)->count();

        $total4 = \app\admin\model\User::where('tuijianid', $userId)->count();

        unset($where['createtime']);
        $tdeep = $this->auth->getUser()->tdeep;
        $where['tdeep'] = $tdeep + 2;
        $total5 = \app\admin\model\User::where($where)->count();

        $type = $this->request->post('type', 1);
        $date = $this->request->post('date', $month);
        $where['tdeep'] = $tdeep + $type;
        $where['createtime'] = ['>=', strtotime($date)];
        $lists = \app\admin\model\User::field('id,avatar,username,nickname,createtime')->where($where)->paginate($pageSize)->each(function ($item) {
            $item['createtime'] = date('Y/m/d', $item['createtime']);
        });

//        var_dump(\app\admin\model\User::getLastSql());die;

        $this->success('数据为', ['total' => $total, 'total1' => $total1, 'total2' => $total2, 'total3' => $total3, 'total4' => $total4, 'total5' => $total5, 'lists' => $lists]);
    }

    /**
     * 会员反馈
     */
    public function suggest()
    {
        $id = $this->auth->id;
        $content = $this->request->post('content');
        if (!$content) {
            $this->error('必须输入内容！');
        }
        $data = [
            'user_id' => $id,
            'content' => $content
        ];

        $res = Suggest::create($data);
        if (!$res->id) {
            $this->error('反馈失败！');
        }

        $this->success('反馈成功！');
    }

    /**
     * 财务流水
     * @throws \think\exception\DbException
     */
    public function moneyChanges()
    {
        $pageSize = $this->request->post('page_size', 15);
        $moneyType = $this->request->post('moneytype', -1);

        $userId = $this->auth->getUser()->id;
        $where = [
            'targetuserid' => $userId,
            'moneytype' => $moneyType
        ];

        $list = Change::field('change_type,record_type,money,createtime')->where($where)->order('id desc')->paginate($pageSize)->each(function ($item) {
            $changeTypes = config('site.change_types');
            $item['change_type'] = $changeTypes[$item['change_type']];
            $item['createtime'] = date('Y年m月d日 H:i', $item['createtime']);

            if ($item['change_type'] == 30) {
                $orderId = Order::where('orderid', $item['change_type'])->value('id');
                $titles = Listo::where('order_id', $orderId)->column('product_name');
                $titles_str = implode(',', $titles);
                $item['change_type'] = '购买产品' . $titles_str;
            }
        });

        $tongji = [];
        $today = strtotime('today');
        $yes = $today - 24 * 60 * 60;
        if ($moneyType == 1) {
            // 报单积分
            $total = Order::where('mark', 'bill')->where('user_id', $userId)->where('status', '>=', 1)->sum('total');
            $tongji[] = [
                'total' => $total
            ];
        } elseif ($moneyType == 2) {
            // 积分
        } elseif ($moneyType == 3) {
            // 静态现金
            $yes = strtotime('today') - 24 * 60 * 60;
            $total = Change::where('moneytype', 3)->where('targetuserid', $userId)->where('createtime', '>=', $yes)->where('record_type', 1)->sum('money');
            $tongji[] = [
                'total' => $total
            ];
        } elseif ($moneyType == 4) {
            // 动态现金
            $total1 = Change::where('moneytype', 4)->where('targetuserid', $userId)->where('createtime', '>=', $yes)->where('record_type', 1)->where('createtime', '<', $today)->sum('money');
            $total2 = Change::where('moneytype', 4)->where('targetuserid', $userId)->where('createtime', '>=', $today)->where('record_type', 1)->sum('money');
            $tongji[] = [
                'total1' => $total1,
                'total2' => $total2
            ];
        } elseif ($moneyType == 5) {
            // 商城钱包
        } elseif ($moneyType == 6) {
            // 储存钱包
            $total1 = Change::where('moneytype', 10)->where('targetuserid', $userId)->where('createtime', '>=', $yes)->where('record_type', 1)->where('createtime', '<', $today)->sum('money');
            $tongji[] = [
                'total1' => $total1,
            ];
        }

        $data = [
            'tongji' => $tongji,
            'list' => $list
        ];

        $this->success('财务流水', $data);
    }

    /**
     * 今日签到
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function signing()
    {
        $userId = $this->auth->getUser()->id;
        $today = strtotime('today');
        $signInfo = Sign::where('user_id', $userId)->where('createtime', '>=', $today)->find();
        if ($signInfo) {
            $this->error('今日已签到！');
        }

        $sdata = [
            'user_id' => $userId,
        ];

        $res = Sign::create($sdata);
        if (!$res->id) {
            $this->error('签到失败！');
        }

        $this->success('签到成功！');
    }

    public function recharge()
    {
        $money = 100;
        $data = [
            'body' => '测试',
            'remark' => '测试'
        ];
        (new Payment())->pay($data);
    }
}
